package com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.dothantech.lpapi.IAtBitmap;
import com.dothantech.lpapi.LPAPI;
import com.dothantech.printer.IDzPrinter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xiaoxing.zhinenghuacangku_liaocheng.R;
import com.xiaoxing.zhinenghuacangku_liaocheng.R2;
import com.xiaoxing.zhinenghuacangku_liaocheng.di.component.DaggerLiaoCheng_LiKuRuKuComponent;
import com.xiaoxing.zhinenghuacangku_liaocheng.di.module.LiaoCheng_LiKuRuKuModule;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.contract.LiaoCheng_LiKuRuKuContract;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.model.entity.GetDistributeList;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.model.entity.GetUserSpaceListForAutoStore;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.presenter.LiaoCheng_LiKuRuKuPresenter;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.adapter.XianshiAdapter;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.DaoMaster;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.DaoSession;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.LikuBaocunmidnum;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.LikuBaocunmidnumDao;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.NoChongfuSelect;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.NoChongfuSelectDao;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.QuedingMaterial;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.QuedingMaterialDao;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.entity.LinYi_LiKuRuKu;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.entity.RuKuDaiJianQuResult;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.utils.LogWriter;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.utils.PrinterUtil;

import org.greenrobot.greendao.query.QueryBuilder;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_LIAO_CHENG_LI_KU_RU_KU)
public class LiaoCheng_LiKuRuKuActivity extends BaseActivity<LiaoCheng_LiKuRuKuPresenter> implements LiaoCheng_LiKuRuKuContract.View, EasyPermissions.PermissionCallbacks, PrinterUtil.PrinterI {

    @BindView(R2.id.nice_storage)
    NiceSpinner spStorage; //物料下拉选
    @BindView(R2.id.nice_position_cang_wei)
    NiceSpinner spPosition; //仓位下拉选
    @BindView(R2.id.ll_cang_wei)
    LinearLayout llCangWei;
    @BindView(R2.id.ll_sou_suo_wu_liao)
    LinearLayout ll_sou_suo_wu_liao;
    @BindView(R2.id.btn_scan_qr_code)
    Button btnScanQrCode;
    @BindView(R2.id.btn_generate_tags)
    Button btnGenerateTags;
    @BindView(R2.id.btn_confirm_storage)
    Button btnConfirmStorage;
    @BindView(R2.id.btn_scan_mid)
    Button btnScanMid; //扫描物料二维码(有二维码的质检样品)
    @BindView(R2.id.cb_er_wei_ma)
    CheckBox cbErWeiMa; //扫描物料二维码(有二维码的质检样品)
    @BindView(R2.id.cb_zi_dong_ku_wei)
    CheckBox cbZiDongKuWei; //是否自动选择库位
    @BindView(R2.id.et_dan_hao)
    EditText etDanHao;
    @BindView(R2.id.et_xiang_mu_ming_cheng)
    EditText etXiangMuMingCheng;
    @BindView(R2.id.et_xiang_mu_bian_hao)
    EditText etXiangMuBianHao;
    @BindView(R2.id.et_wu_liao_ming_cheng)
    EditText etWuLiaoMingCheng;
    @BindView(R2.id.et_gong_ying_shang)
    EditText etGongYingShang;
    @BindView(R2.id.tv_cha_xun)
    TextView tvChaXun;
    @BindView(R2.id.et_weizhi)
    EditText etWeizhi;
    @BindView(R2.id.tv_check)
    TextView tvCheck;
    @BindView(R2.id.tv_agv_huan_chong_wei)
    TextView tvAgvHuanChongWei;
    @BindView(R2.id.tv_yi_sao_miao_tuo_pan_ma)
    TextView mTvYiSaoMiaoTuoPanMa;
    @BindView(R2.id.et_num)
    EditText et_num;
    @BindView(R2.id.et_remark)
    ListView lv_xianshi;
    EditText et_remark;
    PrinterUtil mPrinterUtil;
    TextView tv_huanchongwei;
    Button btn_commit_ruku;
    LikuBaocunmidnumDao likuBaocunmidnumDao;
    NoChongfuSelectDao noChongfuSelectDao;
    QuedingMaterialDao quedingMaterialDao;
    TextView tv_chakan;
    List<QuedingMaterial> listy;
    XianshiAdapter mAdapters;
    Button btn_commit_ruku_hcw;
    Button btn_sao_miao_yi_wei_ma;
    LinearLayout ll_rukuwei;
    boolean diaoyong = false;
    private BottomDialogUtil mBottomDialogUtilShare;
    private boolean isScan = false; //是否扫描二维码
    private boolean isGenerateTags = false; // 是否生成、打印标签
    private boolean isConfirmStorage = false; //是否确定入库
    private int did = 0;
    private double num = 0;
    private String imgStr = "";
    private String cangWeiPosition = "";
    private String mid = "";
    private String instoreBufferId = "";
    private int mSelectedSpid = 0;
    private String spname = "";
    private String id = "";
    private int duiduojixuhao = 0; //1 表示电表 要入2号堆垛机   0 其他物料 入1号堆垛机
    private TextWatcher numTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String etNum = et_num.getText().toString();
            if (!TextUtils.isEmpty(etNum) && Double.parseDouble(etNum) > 0) {
                if (Double.parseDouble(etNum) > num) {
                    et_num.setText(num + "");
                    showMessage("数量不能大于" + num);
                    return;
                }
//                num = Double.parseDouble(et_num.getText().toString());
            }


        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private String mOrderNo = "";
    private String mWuLiaoMingCheng = "";
    private String mXiangMuBianHao = "";
    private LogWriter mLogWriter;
    private int mGid = 0;
    private String mSptname;
    private String mScanSpid = "";
    /**
     * 初始化缓冲位列表下拉选
     */
    private ArrayList<String> mSpids;
    private String mScanMid = "";
    private boolean isRuKuDaiJianKu = false;
    private String mTuoPanMa = "";
    private boolean isBack = false; //判断是不是退出操作

    public static byte[] strToByteArray(String str) {
        if (str == null) {
            return null;
        }
        byte[] byteArray = str.getBytes();
        return byteArray;
    }

    public static Bitmap getBitmap(String filePath) {

        Bitmap bitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
                (double) options.outWidth / 1024f,
                (double) options.outHeight / 1024f)));
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(filePath, options);

        return bitmap;
    }


    private void showQueDingRuKuDialog() {
        new QMUIDialog.CheckBoxMessageDialogBuilder(this)
                .setTitle("确认入库?")
                .setMessage("确认入库?")
                .setChecked(true)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        queDingRuKu();
                        dialog.dismiss();

                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiaoCheng_LiKuRuKuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .liaoCheng_LiKuRuKuModule(new LiaoCheng_LiKuRuKuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.zhi_neng_cang_ku_liao_cheng_activity_storage; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

//        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_lin_yi__li_ku_ru_ku));
        //getLinYi_LiKuRuKuData();
        mTuoPanMa = "";
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(LiaoCheng_LiKuRuKuActivity.this, "text1-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        likuBaocunmidnumDao = daoSession.getLikuBaocunmidnumDao();
        noChongfuSelectDao = daoSession.getNoChongfuSelectDao();
        quedingMaterialDao = daoSession.getQuedingMaterialDao();
        tv_huanchongwei = findViewById(R.id.tv_huanchongwei);
        btn_commit_ruku = findViewById(R.id.btn_commit_ruku);
        et_remark = findViewById(R.id.et_remark);
        tv_chakan = findViewById(R.id.tv_chakan);
        lv_xianshi = findViewById(R.id.lv_xianshi);
        btn_commit_ruku_hcw = findViewById(R.id.btn_commit_ruku_hcw);
        btn_sao_miao_yi_wei_ma = findViewById(R.id.btn_sao_miao_yi_wei_ma);
        btn_sao_miao_yi_wei_ma.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent newIntent = new Intent(getContext(), LiaoCheng_ScanQRCodeActivity.class);
                mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 103);
                // 开始一个新的 Activity等候返回结果
                startActivityForResult(newIntent, 103);
            }
        });
        ll_rukuwei = findViewById(R.id.ll_rukuwei);
        btn_commit_ruku_hcw.setVisibility(View.GONE);
        ll_rukuwei.setVisibility(View.GONE);
        File logf = new File(Environment.getExternalStorageDirectory() + File.separator + "cangkuguanli-" + ArmsUtils.getDataTime("yyyy-MM-dd HH:mm") + ".txt");
        try {
            mLogWriter = LogWriter.open(logf.getAbsolutePath());
        } catch (Exception e) {
        }

//        ToolbarUtils.initToolbarTitleBack(this, "入库");
        mPrinterUtil = new PrinterUtil(this);
        mPrinterUtil.setPrinterI(this);
        IDzPrinter.Factory.getInstance().init(this, mPrinterUtil.mCallback);

        Toolbar toolbar = findViewById(R.id.toolbar);
        TextView tvTitle = findViewById(R.id.title);

        tvTitle.setText("入库");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                killMyself();
            }
        });

        PhotoUtil.init(this, new FrescoIniter());
//        btnGenerateTags.setEnabled(false);
        btnConfirmStorage.setEnabled(false);
        et_num.addTextChangedListener(numTextWatcher);


        btnScanQrCode.setText("扫描库位或扫描缓冲位");
        cbErWeiMa.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isRuKuDaiJianKu)
                    if (isChecked) {
                        btnScanMid.setVisibility(View.VISIBLE);
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
                        btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnScanMid.setEnabled(true);

                        ll_sou_suo_wu_liao.setVisibility(View.GONE);
                        spStorage.setVisibility(View.GONE);
                        et_num.setVisibility(View.GONE);
//                        btnGenerateTags.setVisibility(View.GONE);
                    } else {
                        btnScanMid.setVisibility(View.GONE);
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnScanQrCode.setEnabled(true);
                        btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanMid.setEnabled(false);

                        ll_sou_suo_wu_liao.setVisibility(View.VISIBLE);
                        spStorage.setVisibility(View.VISIBLE);
                        et_num.setVisibility(View.VISIBLE);
//                        btnGenerateTags.setVisibility(View.VISIBLE);

                    }
            }
        });
        cbErWeiMa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRuKuDaiJianKu) {
                    showMessage("您扫描的二维码在入库待检区库位中");
                }
            }
        });
        cbZiDongKuWei.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    getAutoChooseUserSpaceForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID));
                } else {
//                    try {
//                        List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = new ArrayList<>();
//                        initSpPosition(getUserSpaceListForAutoStoreList);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                }
            }
        });

        btn_commit_ruku.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("LongLogTag")
            @Override
            public void onClick(View v) {

                queDingRuKu();
            }
        });
        tv_chakan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listy = new ArrayList<>();
                mAdapters = new XianshiAdapter(LiaoCheng_LiKuRuKuActivity.this, listy);
                lv_xianshi.setAdapter(mAdapters);
                ArrayList<QuedingMaterial> listss = (ArrayList<QuedingMaterial>) queryUserListqd();
                mAdapters.addAll(listss);
            }
        });

        btn_commit_ruku_hcw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoading();
                String methodName = "InstoreQuality";
                SoapParams params = null;
                params = new SoapParams();
                params.put("did", String.valueOf(did));
                params.put("instorebufferid", id);
                params.put("uid", String.valueOf(mSharedPreferencesHelper.getString(BaseConstants.UID)));
                params.put("num", et_num.getText().toString());
                params.put("status", String.valueOf(1));
                params.put("remark", et_remark.getText().toString().trim());
                params.put("imgStr", imgStr);

                SoapUtil.getInstance(LiaoCheng_LiKuRuKuActivity.this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
                    @Override
                    public void onSuccess(int statusCode, SoapObject object) {
                        hideLoading();
                        String result = object.getProperty(methodName + "Result").toString();
                        if (!result.equals("-1") && !result.equals("Error") && !result.equals("-100")) {
                            Toast.makeText(LiaoCheng_LiKuRuKuActivity.this, "暂入缓冲位成功", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(LiaoCheng_LiKuRuKuActivity.this, "暂入缓冲位成功", Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, String content, Throwable error) {
                        hideLoading();
                    }

                    @Override
                    public void onFailure(int statusCode, SoapFault fault) {
                        hideLoading();
                    }
                }, getAapiUserName(), getApiPwd());
            }
        });


        try { //进入页面是判断是否有之前的任务，有任务清空
            ArrayList<LikuBaocunmidnum> listss = (ArrayList<LikuBaocunmidnum>) queryUserListyanshouss();
            if (listss != null && listss.size() > 0) {
                showHasTaskConfirmMessageDialog();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


//        try {
//            for (int i = 0; i < 100; i++) {
//                likuBaocunmidnumDao.insert(new LikuBaocunmidnum(i + "", i + ""));
//            }
//
//            ArrayList<LikuBaocunmidnum> listss = (ArrayList<LikuBaocunmidnum>) queryUserListyanshouss();
//            JSONArray jsonArray = (JSONArray) JSON.toJSON(listss);
//            LogUtils.debugEInfo("modelJson==" + jsonArray.toJSONString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    public void queDingRuKu() {
        if (mSelectedSpid > 0) {
            if (TextUtils.isEmpty(mTuoPanMa)) {
                showMessage("请扫描托盘码");
                return;
            }

            showLoading();
            ArrayList<LikuBaocunmidnum> listss = (ArrayList<LikuBaocunmidnum>) queryUserListyanshouss();
            JSONArray jsonArray = (JSONArray) JSON.toJSON(listss);
//                    String methodName = "InstoreCallliKuGroup";
            String methodName = "InstoreCallliKuGroupWithSALVERID";
            SoapParams params = new SoapParams();
            params.put("modelJson", jsonArray.toJSONString());
            params.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
//                params.put("instoreBufferId", id);
            params.put("spid", String.valueOf(mSelectedSpid));
            log("=========入库提交时的mSelectedSpid=" + mSelectedSpid);

            params.put("remark", et_remark.getText().toString().trim());
            params.put("SALVERID", mTuoPanMa);

            SoapUtil.getInstance(LiaoCheng_LiKuRuKuActivity.this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
                @Override
                public void onSuccess(int statusCode, SoapObject object) {
                    hideLoading();

                    String result = object.getProperty(methodName + "Result").toString();
                    int a = Integer.parseInt(result);
                    if (a > 0) {
                        Toast.makeText(LiaoCheng_LiKuRuKuActivity.this, "发送成功", Toast.LENGTH_LONG).show();
//                                showMessage("发送成功");
//                                getDistributeList(mSharedPreferencesHelper.getString(BaseConstants.UID), getDanHao(), getXiangMuMingCheng(), getWuLiaoMingCheng(), getXiangMuBianHao(), getGongYingShang());
//                                getUserSpaceListForAutoStore(getCangWei());
                        mTuoPanMa = "";//入库成功后把托盘码置空
                        //入库任务发送成功后，重新查询物料
                        onChaXunClicked();

                        likuBaocunmidnumDao.deleteAll();
                    } else {
                        Toast.makeText(LiaoCheng_LiKuRuKuActivity.this, "入库失败", Toast.LENGTH_LONG).show();
                        showMessage("入库失败");
//                        likuBaocunmidnumDao.deleteAll();
                    }
                }

                @Override
                public void onFailure(int statusCode, String content, Throwable error) {
                    hideLoading();

                }

                @Override
                public void onFailure(int statusCode, SoapFault fault) {
                    hideLoading();

                }
            }, getAapiUserName(), getApiPwd());
        } else {
            Toast.makeText(LiaoCheng_LiKuRuKuActivity.this, "请选择入库仓位", Toast.LENGTH_LONG).show();
        }
    }

    //自动获得库位
    private void getAutoChooseUserSpaceForAutoStore(String user_id) {
        showLoading();

//        String methodName = "AutoChooseUserSpaceForAutoStore";
        String methodName = "AutoChooseUserSpaceForAutoStoreQingDao";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("ismeter", String.valueOf(duiduojixuhao));
        params.put("did", String.valueOf(did));//运输计划ID
        LogUtils.debugEInfo("ismeter==" + duiduojixuhao);


        /**
         * 请求
         */

        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {

                    String result = object.getProperty(methodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = new Gson().fromJson(result, GetUserSpaceListForAutoStore.class);

                        List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = new ArrayList<>();
                        if (getUserSpaceListForAutoStore != null) {
                            getUserSpaceListForAutoStoreList.add(getUserSpaceListForAutoStore);
                            initSpPosition(getUserSpaceListForAutoStoreList);
                        }


                    } else {
                        if (spPosition != null) {
                            spPosition.clearData();
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }


//    private void getLinYi_LiKuRuKuData() {
//        HashMap<String, String> map = new HashMap<>();
//
//        mPresenter.getLinYi_LiKuRuKuData(map);
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {

                mScanSpid = extras.getString("scan_result");
                //判断扫描的二维码是否在返回的列表中(二维码为spid)
                if (mSpids.contains(mScanSpid)) { //在的话mScanSpid = spid
                    isRuKuDaiJianKu = true;
//                    btnGenerateTags.setVisibility(View.GONE);
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                    btnConfirmStorage.setEnabled(true);
                    btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnScanQrCode.setEnabled(false);
                    hideCangWei();

                } else { //不在的话，给个提示，instoreBufferId = spid ，然后把mScanSpid置为空
                    isRuKuDaiJianKu = false;
                    mScanSpid = "";
                    showCangWei();
                    if (!cbErWeiMa.isChecked()) {
                        instoreBufferId = extras.getString("scan_result");
                        setInstoreBufferReadyForAGV(instoreBufferId, spname);
                    } else if (cbErWeiMa.isChecked()) {
                        instoreBufferId = extras.getString("scan_result");
//                        btnGenerateTags.setVisibility(View.GONE);
                        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnConfirmStorage.setEnabled(true);
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
                        btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanMid.setEnabled(false);

                    } else {
                        showMessage("您扫描的二维码不在入库待检区库位中");
                    }

                }

            }

        } else if (resultCode == 102) {//扫描物料二维码(有二维码的质检样品)
            Bundle extras = data.getExtras();
            mid = extras.getString("scan_result");
            mScanMid = mid;
//            btnGenerateTags.setVisibility(View.GONE);


            btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnConfirmStorage.setEnabled(false);
            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
            btnScanQrCode.setEnabled(true);
            btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanMid.setEnabled(false);

        } else if (resultCode == 103) {//扫描物料二维码(有二维码的质检样品)
            Bundle extras = data.getExtras();
            mTuoPanMa = extras.getString("scan_result");
            mTvYiSaoMiaoTuoPanMa.setText("已扫描托盘码: " + mTuoPanMa);
            LogUtils.debugEInfo("mTuoPanMa=" + mTuoPanMa);
        } else {
            if (resultCode != 0)
                PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    private void hideCangWei() {

        spPosition.setVisibility(View.GONE);
        llCangWei.setVisibility(View.GONE);
        btn_commit_ruku.setVisibility(View.GONE);
        btn_commit_ruku_hcw.setVisibility(View.VISIBLE);
    }

    private void showCangWei() {

        spPosition.setVisibility(View.VISIBLE);
        llCangWei.setVisibility(View.VISIBLE);
    }

    private void setInstoreBufferReadyForAGV(String bufferId, String spid) {
        showLoading();

        String methodName = "SetInstoreBufferReadyForAGV";

        SoapParams params = new SoapParams();
        params.put("bufferId", bufferId);
        params.put("spname", spid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (result.equals("false")) {
                        LogUtils.debugEInfo("resultresultresultresult=" + result);
                        showMessage("缓冲位置不可用，请联系管理员");
                    } else {

                        isScan = true;
                        tvAgvHuanChongWei.setVisibility(View.VISIBLE);
                        tvAgvHuanChongWei.setText(new StringBuilder().append("已选择的Agv缓冲位置：").append(instoreBufferId));

                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
//                        btnGenerateTags.setBackgroundColor(getResources().getColor(R.color.public_red));
                        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
//                        btnGenerateTags.setEnabled(true);
                        btnConfirmStorage.setEnabled(false);
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
            xiuGaiTouXiang();
        }
    }


    private void xiuGaiTouXiang() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(LiaoCheng_LiKuRuKuActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    log("相册选择图片：");
//                                    if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {
//                                        createMaterialForInstoreAuto(compressedPath);
//                                    } else {
//                                        imgStr = ArmsUtils.fileToBase64(compressedPath);
//                                    }

                                    if (isRuKuDaiJianKu) {
                                        imgStr = ArmsUtils.bitmapToString(compressedPath);
                                    } else if (!isRuKuDaiJianKu && !TextUtils.isEmpty(mScanMid) && cbErWeiMa.isChecked()) {

                                    } else if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {

                                        createMaterialForInstoreAuto(compressedPath);
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log(e.getMessage());

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(LiaoCheng_LiKuRuKuActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    log("相机拍照：");
//                                    if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {
//                                        createMaterialForInstoreAuto(compressedPath);
//                                    } else {
//                                        imgStr = ArmsUtils.fileToBase64(compressedPath);
//                                    }

                                    if (isRuKuDaiJianKu) {
                                        imgStr = ArmsUtils.bitmapToString(compressedPath);
                                    } else if (!isRuKuDaiJianKu && !TextUtils.isEmpty(mScanMid) && cbErWeiMa.isChecked()) {

                                    } else if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {
                                        createMaterialForInstoreAuto(compressedPath);
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log(e.getMessage());

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(LiaoCheng_LiKuRuKuActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    /**
     * @param
     * @return
     * @method
     * @description 生成mid，标签
     * @date: 2020/7/3 0003 8:53
     * @author: 小星
     */
    private void createMaterialForInstoreAuto(String compressedPath) throws Exception {
        imgStr = ArmsUtils.bitmapToString(compressedPath);
//        HashMap<String, String> map = new HashMap<String, String>();
        SoapParams params = new SoapParams();
        params.put("did", String.valueOf(did));//运输计划ID
        params.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("num", et_num.getText().toString());
        params.put("imgStr", String.valueOf(imgStr));
        log("调用上传图片接口");

//        mPresenter.createMaterialForInstoreAuto(StorageActivity.this, map);
        createMaterialForInstoreAuto(params);
    }

    /**
     * @param
     * @return
     * @method
     * @description 生成mid，标签
     * @date: 2020/7/3 0003 8:53
     * @author: 小星
     */
    private void createMaterialForInstoreAuto(SoapParams params) {
        showLoading();

        String methodName = "CreateMaterialForInstoreAuto";


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (!result.equals("-1")) {
                        mid = result;
                        likuBaocunmidnumDao.insert(new LikuBaocunmidnum(mid, et_num.getText().toString()));
                        log("上传图片成功后返回的要打印的mid：" + result);
                        try {
                            LogUtils.debugEInfo("CreateMaterialForInstoreAuto--打印二维码。。。。。");
                            if (mSharedPreferencesHelper.getString(BaseConstants.ER_WEI_MA_TYPE).equals("1")) {
                                printQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                            } else {
//                                printBigQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                                printBigQRcodeOriention(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                            }
//                            printYiWeiMaQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);

                        } catch (Exception e) {
                            log(e.getMessage());
                        }
                    } else {
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 小的纸张 50x20 的
     *
     * @param content
     * @param orderNo
     * @param name
     * @param num
     * @param time
     * @param proid
     */
    private void printQRcode(String content, String orderNo, String name, String num, String time, String proid) {
//        if (mPrinterUtil.selectPrinterCheck()) {
        log("初始化打印二维码printQRcode");

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 20 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 0 * 100, 1 * 100, 15 * 100);//  9, 10, 20,30
        api.drawText("订单号:" + orderNo, 16 * 100, 0 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        if (name.length() > 15) {
            if (name.substring(15).length() > 20) {
                api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 16 * 100, 96 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15, 35), 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(35), 16 * 100, 15 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 16 * 100, 18 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            } else {
                api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15), 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 16 * 100, 15 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            }

        } else {
            api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("物料名称:" + name, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
            api.drawText("入库时间:" + time, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
        log("二维码打印成功printQRcode");

        //打印完二维码弹出确定入库的按钮
        showQueDingRuKuDialog();

//        }
    }

    /**
     * 大的纸张 50x50的
     *
     * @param content
     * @param orderNo
     * @param name
     * @param num
     * @param time
     * @param proid
     */
    private void printBigQRcode(String content, String orderNo, String name, String num, String time, String proid) {
//        if (mPrinterUtil.selectPrinterCheck()) {
        log("初始化打印二维码printBigQRcode");

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 50 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 10 * 100, 6 * 100, 25 * 100);//  9, 10, 20,30
        api.drawText("订单号:" + orderNo, 0 * 100, 32 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        if (name.length() > 25) {
            if (name.substring(25).length() > 20) {
                api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15, 35), 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(35), 0 * 100, 47 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 0 * 100, 50 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            } else {
                api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15), 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 0 * 100, 47 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            }

        } else {
            api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("物料名称:" + name, 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
            api.drawText("入库时间:" + time, 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
        log("二维码打印成功printBigQRcode");
        //打印完二维码弹出确定入库的按钮
        showQueDingRuKuDialog();

//        }
    }

    private void printYiWeiMaQRcode(String content, String orderNo, String name, String num, String time, String proid) {
//        if (mPrinterUtil.selectPrinterCheck()) {
        log("初始化打印二维码printBigQRcode");

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 50 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw1DBarcode(content, 5 * 100, 0 * 100, 35 * 100, 15 * 100);
        api.draw2DQRCode(content, 5 * 100, 20 * 100, 20 * 100);
        api.drawText("核对序号:" + content, 5 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);

//        api.drawText("订单号:" + orderNo, 0 * 100, 32 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//        if (name.length() > 25) {
//            if (name.substring(25).length() > 20) {
//                api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("物料名称:" + name.substring(0, 15), 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("" + name.substring(15, 35), 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("" + name.substring(35), 0 * 100, 47 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
////                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
//                api.drawText("入库时间:" + time, 0 * 100, 50 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            } else {
//                api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("物料名称:" + name.substring(0, 15), 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("" + name.substring(15), 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
////                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
//                api.drawText("入库时间:" + time, 0 * 100, 47 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            }
//
//        } else {
//            api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("物料名称:" + name, 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
////            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
//            api.drawText("入库时间:" + time, 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
        log("二维码打印成功printBigQRcode");

//        }
    }

    public void log(String msg) {

        try {
            mLogWriter.print(LiaoCheng_StorageActivity.class, msg);
        } catch (Exception e) {
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            return true;
        }

        return super.onKeyDown(keyCode, event);


    }

    private void showConfirmMessageDialog() {
        new QMUIDialog.CheckBoxMessageDialogBuilder(this)
                .setTitle("确认退出?")
                .setMessage("已扫描缓冲位,确认退出?")
                .setChecked(true)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        cancelBufferReadyForAGV();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    /**
     * @param
     * @return
     * @method
     * @description 按手机左上角退出或手机上返回是，清空任务
     * @date: 2020/6/16 0016 11:52
     * @author: 小星
     */
    private void cancelBufferReadyForAGV() {
        showLoading();

        ArrayList<LikuBaocunmidnum> listss = (ArrayList<LikuBaocunmidnum>) queryUserListyanshouss();
        JSONArray jsonArray = (JSONArray) JSON.toJSON(listss);
        String methodName = "RollBackInstoreBatch";
        SoapParams params = new SoapParams();
        params.put("modelJson", jsonArray.toJSONString());
        params.put("instoreBufferId", id);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();

                if (result.equals("true")) {
                    likuBaocunmidnumDao.deleteAll();
                    quedingMaterialDao.deleteAll();
                    noChongfuSelectDao.deleteAll();
                    if (isBack) {
                        isBack = false;
                        finish();
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    public List<LikuBaocunmidnum> queryUserListyanshouss() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(LiaoCheng_LiKuRuKuActivity.this, "text1-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        likuBaocunmidnumDao = daoSession.getLikuBaocunmidnumDao();
        QueryBuilder<LikuBaocunmidnum> qb = likuBaocunmidnumDao.queryBuilder();
        List<LikuBaocunmidnum> list = qb.list();
        return list;
    }

    private void showHasTaskConfirmMessageDialog() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("任务提醒?")
                .setMessage("有之前未执行完的任务，是否继续执行或删除?")
                .addAction("删除任务", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        RollBackInstoreBatch(); //进入页面判断是否有缓存的任务，执行回滚操作，回滚成功，删除本地的任务

                        dialog.dismiss();
                    }
                })
                .addAction("继续执行", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @OnClick({R2.id.btn_scan_qr_code, R2.id.btn_generate_tags, R2.id.btn_confirm_storage, R2.id.btn_scan_mid})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.btn_scan_qr_code) {
            if (getPermission()) {

                if (mSelectedSpid > 0) {

//            Utils.navigation(StorageActivity.this, RouterHub.ZHI_NENG_HUA_CANG_KU_SCAN_QR_CODE_ACTIVITY, 101);
                    Intent newIntent = new Intent(this, LiaoCheng_ScanQRCodeActivity.class);
                    mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
                    // 开始一个新的 Activity等候返回结果
                    startActivityForResult(newIntent, 101);
                } else {
                    showMessage("请先选择仓位");
                }

            }

        } else if (i == R.id.btn_scan_mid) {//扫描物料二维码(有二维码的质检样品)
            if (getPermission()) {


                Intent newIntent = new Intent(this, LiaoCheng_ScanQRCodeActivity.class);
                mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 102);
                // 开始一个新的 Activity等候返回结果
                startActivityForResult(newIntent, 102);


            }

        } else if (i == R.id.btn_generate_tags) {

            if (TextUtils.isEmpty(mTuoPanMa)) {
                showMessage("请扫描托盘码");
                return;
            }

            if (mPrinterUtil.selectPrinterCheck()) {

                //num 用于判断是否选择物料
                if (did > 0 && num > 0) {

//                    if (!isScan) {
//                        showMessage("请先扫描二维码");
//                        return;
//                    }
                    if (getPermission()) {
                        xiuGaiTouXiang();
                    }
                } else {
                    showMessage("请先选择物料");

                }
            }

        } else if (i == R.id.btn_confirm_storage) {
            if (getPermission()) {

                if (isRuKuDaiJianKu) {
                    //入库待检区
                    if (TextUtils.isEmpty(imgStr)) {
                        xiuGaiTouXiang();
                    } else {
                        linYinShouDongRuKu(mid, instoreBufferId, String.valueOf(mSelectedSpid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());
                    }
                } else if (!isRuKuDaiJianKu && !TextUtils.isEmpty(mScanMid) && cbErWeiMa.isChecked()) {
                    //有质检二维码的
                    if (mSelectedSpid > 0) {
                        linYinYouErWeiMaZhiJianYangPin(mScanMid, instoreBufferId, String.valueOf(mSelectedSpid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());
                    } else {
                        showMessage("请先选择仓位");

                    }

                } else if (!isRuKuDaiJianKu && !cbErWeiMa.isChecked()) {
                    //一般入库,没有质检二维码的

                    if (!isScan) {
                        ArmsUtils.makeText(getContext(), "请先扫描二维码");
                        return;
                    }
                    if (!isGenerateTags) {
                        ArmsUtils.makeText(getContext(), "标签没有打印");
                        return;
                    }
                    addAgvTask(mid, String.valueOf(mSelectedSpid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());
                }
            }


        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            return false;
        }

    }

    private void addAgvTask(String mid, String spid, String num, String uid, String remark) {
        showLoading();
        String methodName = "InstoreCallliKu";
        SoapParams params = new SoapParams();

        //(2)入库函数 public string Instore(int did, int spid, int uid, double num, int status, string remark, string imgStr)
        //判断mScanSpid是否为空，不为空二维码在返回的仓位列表中，执行Instore 方法，为空的话执行InstoreCallAGV 方法
//        if (!TextUtils.isEmpty(mScanSpid)) {
//            methodName = "Instore";
//            params.put("did", String.valueOf(did));
//            params.put("spid", mScanSpid);
//            params.put("uid", uid);
//            params.put("num", num);
//            params.put("status", "2");
//            params.put("remark", remark);
//            params.put("imgStr", imgStr);
//        } else if (cbErWeiMa.isChecked()) {
//            methodName = "InstoreCallAGVFromQualityZone";
//            params.put("mid", mid);
//            params.put("instoreBufferId", instoreBufferId);
//            params.put("spid", spid);
//            params.put("num", num);
//            params.put("uid", uid);
//            params.put("remark", remark);
//        } else {
        params.put("mid", mid);
//        params.put("instoreBufferId", instoreBufferId);
        params.put("spid", spid);
        params.put("num", num);
        params.put("uid", uid);
        params.put("remark", remark);
//        }


        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    isGenerateTags = false;
                    isRuKuDaiJianKu = false;
                    isScan = false;
                    btnScanQrCode.setBackgroundColor(getResources().getColor(R.color.public_red));
//                    btnGenerateTags.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnScanQrCode.setEnabled(true);
//                    btnGenerateTags.setEnabled(false);
                    btnConfirmStorage.setEnabled(false);
                    onChaXunClicked();
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void linYinYouErWeiMaZhiJianYangPin(String mid, String instoreBufferId, String spid, String num, String uid, String remark) {
        showLoading();
        String methodName = "InstoreCallAGVFromQualityZone";
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("instoreBufferId", instoreBufferId);
        params.put("spid", spid);
        params.put("uid", uid);
        params.put("remark", remark);


        /**
         * 请求
         */

        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("-1")) {
                    mScanMid = "";
                    showMessage("发送成功");
                    isGenerateTags = false;
                    isScan = false;
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnConfirmStorage.setEnabled(false);
                    btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnScanQrCode.setEnabled(false);
                    btnScanMid.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                    btnScanMid.setEnabled(true);
                    onChaXunClicked();
//                    cangWeiChaXun();
                } else {
                    showMessage("入库失败");
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void linYinShouDongRuKu(String mid, String instoreBufferId, String spid, String num, String uid, String remark) {
        showLoading();
        String methodName = "Instore";
        SoapParams params = new SoapParams();
        params.put("did", String.valueOf(did));
        params.put("spid", mScanSpid);
        params.put("uid", uid);
        params.put("num", num);
        params.put("status", "2");
        params.put("remark", remark);
        params.put("imgStr", imgStr);


        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("-1")) {
                    showMessage("发送成功");
                    btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                    btnScanQrCode.setEnabled(true);
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnConfirmStorage.setEnabled(false);
                    try {
                        RuKuDaiJianQuResult ruKuDaiJianQuResult = new Gson().fromJson(result, RuKuDaiJianQuResult.class);
                        result = String.valueOf(ruKuDaiJianQuResult.getMid());
                        if (mSharedPreferencesHelper.getString(BaseConstants.ER_WEI_MA_TYPE).equals("1")) {
                            printQRcode(result, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                        } else {
//                            printBigQRcode(result, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                            printBigQRcodeOriention(result, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                        }
                    } catch (Exception e) {
                        log(e.getMessage());
                    }
                    onChaXunClicked();
//                    cangWeiChaXun();

                } else {
                    showMessage("入库失败");
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    public void printBigQRcodeOriention(String content, String orderNo, String name, String num, String time, String proid) {

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.setItemHorizontalAlignment(LPAPI.ItemAlignment.LEFT);
        api.setItemOrientation(180);

        api.startJob(50 * 100, 50 * 100);//48, 50
//        api.setItemOrientation(180);

        // 开始一个页面的绘制，绘制二维码
        if (name.length() > 19) {
            if (name.substring(19).length() > 23) {
                api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(42), 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(19, 42), 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 19), 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("核对序号:" + content, 46 * 100, 19 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("订单号:" + orderNo, 46 * 100, 22 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.draw2DQRCode(content, 14 * 100, 23 * 100, 17 * 100);//  9, 10, 20,30
            } else {
                api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(19), 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 19), 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("核对序号:" + content, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("订单号:" + orderNo, 46 * 100, 19 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.draw2DQRCode(content, 14 * 100, 20 * 100, 20 * 100);//  9, 10, 20,30
            }

        } else {
            api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("物料名称:" + name, 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("项目编号:" + proid, 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("核对序号:" + content, 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
            api.drawText("订单号:" + orderNo, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.draw2DQRCode(content, 14 * 100, 17 * 100, 20 * 100);//  9, 10, 20,30
        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
        showQueDingRuKuDialog();

    }

    @OnClick(R2.id.tv_cha_xun)
    public void onChaXunClicked() {

        if (TextUtils.isEmpty(getDanHao())
                && TextUtils.isEmpty(getXiangMuMingCheng())
                && TextUtils.isEmpty(getXiangMuBianHao())
                && TextUtils.isEmpty(getWuLiaoMingCheng())
                && TextUtils.isEmpty(getGongYingShang())) {

            showMessage("至少输入一个查询条件");
            return;

        }

        if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.UID))) {
            showMessage("请先登录");
            return;
        }
        showCangWei();
//        mPresenter.getDistributeList(this, mSharedPreferencesHelper.getString(BaseConstants.UID), getDanHao(), getXiangMuMingCheng(), getWuLiaoMingCheng(), getXiangMuBianHao(), getGongYingShang());
        getDistributeList(mSharedPreferencesHelper.getString(BaseConstants.UID), getDanHao(), getXiangMuMingCheng(), getWuLiaoMingCheng(), getXiangMuBianHao(), getGongYingShang());
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        showMessage("相关权限获取成功");

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        showMessage("请同意相关权限，否则功能无法使用");

    }

    /**
     * 初始化入库列表下拉选
     */
    private void initSpStorage(List<GetDistributeList> distributeLists) {


        ArrayList<String> list = new ArrayList<String>();
        HashMap<String, GetDistributeList> getDistributeListHashMap = new HashMap<>();

        if (distributeLists.size() > 0) {
            for (int i = 0; i < distributeLists.size(); i++) {
                list.add(String.valueOf(
                        new StringBuilder()
                                .append(distributeLists.get(i).getProjectName())
                                .append("-")
                                .append(distributeLists.get(i).getMaterial())
                                .append("-")
                                .append(distributeLists.get(i).getDid())
                ));
                getDistributeListHashMap.put(distributeLists.get(i).getProjectName() + "-" + distributeLists.get(i).getMaterial() + "-" + distributeLists.get(i).getDid(), distributeLists.get(i));

            }
            if (list.size() > 0) {

                spStorage.attachDataSource(list);

                if (spStorage.getDataSet().size() > 0) {

                    GetDistributeList getDistributeList = getDistributeListHashMap.get(spStorage.getFullWidthAdapter().getItem(0));

                    did = getDistributeList.getDid();
                    num = getDistributeList.getDnum();
                    et_num.setText(String.valueOf(num));
                    mOrderNo = getDistributeList.getPurchaseid();//打印二维码的订单号
                    mWuLiaoMingCheng = getDistributeList.getMaterial();//打印二维码的物料名称
                    mXiangMuBianHao = getDistributeList.getProid();//打印二维码的项目编号
                    mGid = getDistributeList.getGid();
                    duiduojixuhao = getDistributeList.getIselecmeter();
                    LogUtils.debugEInfo("did=====" + did);

                    LogUtils.debugEInfo("duiduojixuhao==" + duiduojixuhao);
                }

                spStorage.setGravity(Gravity.LEFT);
                spStorage.addOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        GetDistributeList getDistributeList = getDistributeListHashMap.get(spStorage.getFullWidthAdapter().getItem(position));

                        did = getDistributeList.getDid();
                        num = getDistributeList.getDnum();
                        mOrderNo = getDistributeList.getPurchaseid();
                        mWuLiaoMingCheng = getDistributeList.getMaterial();
                        mXiangMuBianHao = getDistributeList.getProid();
                        mGid = getDistributeList.getGid();
                        et_num.setText(String.valueOf(num));
                        duiduojixuhao = getDistributeList.getIselecmeter();
                        LogUtils.debugEInfo("did=====" + did);
                        LogUtils.debugEInfo("duiduojixuhao==" + duiduojixuhao);


                        quedingMaterialDao.insert(new QuedingMaterial(getDistributeList.getProjectName(), getDistributeList.getMaterial(), et_num.getText().toString()));

//                    ArrayList<NoChongfuSelect> list1= (ArrayList<NoChongfuSelect>) queryUserList();
//                    if (list1.size()>0){
//                        for (int i=0;i<list1.size();i++){
//                            if (!list1.get(i).getDid().contains(String.valueOf(did))){
//                                noChongfuSelectDao.insert(new NoChongfuSelect(String.valueOf(did)));
//                            }else {
//                                list.add("");
//                                spStorage.attachDataSource(list);
//                                Toast.makeText(LiaoCheng_LiKuRuKuActivity.this,"请不要重复选择",Toast.LENGTH_LONG).show();
//                            }
//
//                        }
//                    }else {
//                        noChongfuSelectDao.insert(new NoChongfuSelect(String.valueOf(did)));
//                    }

                    }
                });
            }

        } else {
            showMessage("未查询到该物料，请重新c");
            list.add("");
            spStorage.attachDataSource(list);
            spStorage.setGravity(Gravity.LEFT);

        }


//        cangWeiChaXun();

    }

    public List<NoChongfuSelect> queryUserList() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(LiaoCheng_LiKuRuKuActivity.this, "text1-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        noChongfuSelectDao = daoSession.getNoChongfuSelectDao();
        QueryBuilder<NoChongfuSelect> qb = noChongfuSelectDao.queryBuilder();
        List<NoChongfuSelect> list = qb.list();
        return list;
    }

    public List<QuedingMaterial> queryUserListqd() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(LiaoCheng_LiKuRuKuActivity.this, "text1-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        quedingMaterialDao = daoSession.getQuedingMaterialDao();
        QueryBuilder<QuedingMaterial> qb = quedingMaterialDao.queryBuilder();
        List<QuedingMaterial> list = qb.list();
        return list;
    }

    @OnClick(R2.id.tv_check)
    public void cangWeiChaXun() {
//        if (TextUtils.isEmpty(getCangWei())) {
//            ArmsUtils.makeText(this, "请输入仓位的名称");
//            return;
//        }
        getUserSpaceListForAutoStore(getCangWei());

    }

    /**
     * 查询仓位
     *
     * @param spname
     */
    private void getUserSpaceListForAutoStore(String spname) {
//        mPresenter.getUserSpaceListForAutoStore(this, mSharedPreferencesHelper.getString(BaseConstants.UID), spname);
        getUserSpaceListForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID), spname, mGid);
    }

    private String getCangWei() {
        return etWeizhi.getText().toString().trim();
    }

    /**
     * 选仓位
     * 用法同GetUserSpaceList
     * 多了一个字段 isauto，表明此仓位是否为立库仓位  用于提示用户
     *
     * @param user_id
     * @param spname  仓位的名字，为空的时候表示查询所有的
     * @return
     */

    @SuppressLint("LongLogTag")
    private void getUserSpaceListForAutoStore(String user_id, String spname, int gid) {
        showLoading();

        String methodName = "GetUserSpaceListForAutoStoreQingDao";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("spname", spname);
        params.put("ismeter", String.valueOf(duiduojixuhao));
        LogUtils.debugEInfo("ismeter==" + duiduojixuhao);

        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    try {

                        List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = ArmsUtils.parseString2List(result, GetUserSpaceListForAutoStore.class);
                        if (getUserSpaceListForAutoStoreList.size() > 0) {

                            initSpPosition(getUserSpaceListForAutoStoreList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void initSpPosition(List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList) {
        ArrayList<String> spnames = new ArrayList<String>();
        ArrayList<String> listSpids = new ArrayList<String>();
        mSpids = new ArrayList<String>();
        HashMap<String, GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreHashMap = new HashMap<>();

        for (int i = 0; i < getUserSpaceListForAutoStoreList.size(); i++) {
            spnames.add(getUserSpaceListForAutoStoreList.get(i).getSpname());
            listSpids.add(String.valueOf(getUserSpaceListForAutoStoreList.get(i).getSpid()));
            if (getUserSpaceListForAutoStoreList.get(i).getSptname().equals("入库待检区")) {
                mSpids.add(String.valueOf(getUserSpaceListForAutoStoreList.get(i).getSpid()));
            }
            getUserSpaceListForAutoStoreHashMap.put(getUserSpaceListForAutoStoreList.get(i).getSpname(), getUserSpaceListForAutoStoreList.get(i));

        }
        spPosition.attachDataSource(spnames);
        if (spPosition.getDataSet().size() > 0) {

            GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = getUserSpaceListForAutoStoreHashMap.get(spPosition.getFullWidthAdapter().getItem(0));

            mSelectedSpid = getUserSpaceListForAutoStore.getSpid();
            spname = getUserSpaceListForAutoStore.getSpname();
            cangWeiPosition = String.valueOf(getUserSpaceListForAutoStore.getSpid());
            mSptname = getUserSpaceListForAutoStore.getSptname();

            LogUtils.debugEInfo("spid==" + mSelectedSpid + "   spname=" + spname);


            if (getUserSpaceListForAutoStore.getSptname().equals("入库待检区")) {
                hideCangWei();
            } else {

                btn_commit_ruku_hcw.setVisibility(View.GONE);
                btn_commit_ruku.setVisibility(View.VISIBLE);
            }
            if (mSptname.equals("入库待检区")) {
//                showMessage("仓管员扫描待检区二维码");
            }
        }


        spStorage.setGravity(Gravity.LEFT);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = getUserSpaceListForAutoStoreHashMap.get(spPosition.getFullWidthAdapter().getItem(position));


                cangWeiPosition = String.valueOf(getUserSpaceListForAutoStore.getSpid());
                mSelectedSpid = getUserSpaceListForAutoStore.getSpid();
                spname = getUserSpaceListForAutoStore.getSpname();
                mSptname = getUserSpaceListForAutoStore.getSptname();
                LogUtils.debugEInfo("spid==" + mSelectedSpid + "   spname=" + spname);


                if (mSptname.equals("入库待检区")) {
//                        showMessage("仓管员扫描待检区二维码");
                }

                if (getUserSpaceListForAutoStore.getSptname().equals("入库待检区")) {
                    btn_commit_ruku.setEnabled(false);
                    btn_commit_ruku_hcw.setEnabled(true);
                    tv_huanchongwei.setText(spname);
                    hideCangWei();

                } else {
                    btn_commit_ruku_hcw.setEnabled(false);
                    btn_commit_ruku.setEnabled(true);
                }

            }
        });
    }

    private String getDanHao() {
        return etDanHao.getText().toString().trim();
    }

    private String getXiangMuMingCheng() {
        return etXiangMuMingCheng.getText().toString().trim();
    }

    private String getXiangMuBianHao() {
        return etXiangMuBianHao.getText().toString().trim();
    }

    private String getWuLiaoMingCheng() {
        return etWuLiaoMingCheng.getText().toString().trim();
    }

    private String getGongYingShang() {
        return etGongYingShang.getText().toString().trim();
    }

    /**
     * 搜索获取物料列表
     *
     * @param user_id
     * @param orderNo
     * @param projectName
     * @param material
     * @param projectNo
     * @param sname
     * @return
     */
    private void getDistributeList(String user_id, String orderNo, String projectName, String material, String projectNo, String sname) {
        showLoading();

        String methodName = "GetDistributeList";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("orderNo", orderNo);
        params.put("projectName", projectName);
        params.put("material", material);
        params.put("projectNo", projectNo);
        params.put("sname", sname);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                //入库任务发送成功后，重新查询仓位

                try {
                    String result = object.getProperty(methodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        List<GetDistributeList> getDistributeLists = ArmsUtils.parseString2List(result, GetDistributeList.class);
                        if (getDistributeLists.size() > 0) {
                            initSpStorage(getDistributeLists);
                        }
                        //                    cangWeiChaXun();

                        if (cbZiDongKuWei.isChecked()) { //如果自动选择库位勾选，则执行自动查询仓位方法
                            getAutoChooseUserSpaceForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID));
                        } else {//如果自动选择库位没有勾选，则执行手动查询仓位方法
                            cangWeiChaXun();
                        }
                    } else {

                        if (spStorage != null) {
                            spStorage.clearData();
                        }
                        //                    List<GetDistributeList> getDistributeLists =ArmsUtils.parseString2List(result, GetDistributeList.class);;
                        //                    initSpStorage(getDistributeLists);
                        //                    cangWeiChaXun();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void printQRcode(String content) {


        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 20 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 0 * 100, 1 * 100, 15 * 100);//  9, 10, 20,30


        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
    }

    @Override
    public void onProgressInfo(String info) {

    }

    @Override
    public void onStateChange(String info) {
        log(info);

    }

    @Override
    public void onPrintProgress(String info) {
        log(info);

    }

    @Override
    public void onPrinterDiscovery(String info) {
        log(info);

    }

    @Override
    public void connectSuccess(String info) {
        log("打印机连接成功，发送通知，刷新界面提示:==" + info);

    }

    @Override
    public void Connecting(String info) {
        log(info);

    }

    @Override
    public void connectFail(String info) {
        log("打印机连接失败、断开连接，发送通知，刷新界面提示:==" + info);

    }

    @Override
    public void printSuccess() {
        log("二维码打印成功");

        showQueDingRuKuBtn();
    }

    private void showQueDingRuKuBtn() {
        isGenerateTags = true;

        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
//        btnGenerateTags.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
        btnScanQrCode.setEnabled(false);
//        btnGenerateTags.setEnabled(false);
        btnConfirmStorage.setEnabled(true);
    }

    @Override
    public void printFail() {
        log("二维码打印失败，请重新打印");
        showMessage("二维码打印失败，请重新打印");
    }

    /**
     * @param
     * @return
     * @method
     * @description 二维码打印失败后，回滚任务
     * @date: 2020/6/16 0016 11:45
     * @author: 小星
     */
    public void RollBackInstoreBatch() {
        showMessage("打印异常");
        showLoading();
        LogUtils.debugEInfo("RollBackInstoreBatch。。。。。");

        ArrayList<LikuBaocunmidnum> listss = (ArrayList<LikuBaocunmidnum>) queryUserListyanshouss();
        JSONArray jsonArray = (JSONArray) JSON.toJSON(listss);
        String methodName = "RollBackInstoreBatch";
        SoapParams params = new SoapParams();
        params.put("modelJson", jsonArray.toJSONString());
        params.put("instoreBufferId", id);

        /**
         * 请求
         */
        SoapUtil.getInstance(LiaoCheng_LiKuRuKuActivity.this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();

                if (result.equals("true")) {
                    likuBaocunmidnumDao.deleteAll();
                    quedingMaterialDao.deleteAll();
                    noChongfuSelectDao.deleteAll();
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void getLiaoCheng_LiKuRuKuDataSuccess(LinYi_LiKuRuKu entityData) {

    }
}
